using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Shared.Services;
using UserService.Data;

var configuration = new ConfigurationBuilder()
    .SetBasePath(Directory.GetCurrentDirectory())
    .AddJsonFile("appsettings.json", optional: false)
    .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Development"}.json", optional: true)
    .AddEnvironmentVariables()
    .Build();

Console.WriteLine("🗄️ 数据库迁移工具");
Console.WriteLine("==================");

var databaseFactory = new DatabaseProviderFactory();
var connectionString = databaseFactory.GetConnectionString(configuration, "Database");
var databaseType = configuration.GetValue<string>("Database:Type") ?? "PostgreSQL";
var provider = databaseFactory.GetProvider(databaseType);

Console.WriteLine($"📊 数据库类型: {databaseType}");
Console.WriteLine($"🔗 连接字符串: {connectionString}");

// 创建DbContext选项
var optionsBuilder = new DbContextOptionsBuilder<UserDbContext>();
provider.ConfigureDbContext(optionsBuilder, connectionString);

using var context = new UserDbContext(optionsBuilder.Options);

try
{
    Console.WriteLine("🔄 开始数据库迁移...");
    
    // 确保数据库已创建
    await context.Database.EnsureCreatedAsync();
    Console.WriteLine("✅ 数据库创建成功");
    
    // 应用迁移
    if (await context.Database.GetPendingMigrationsAsync() is var pendingMigrations && pendingMigrations.Any())
    {
        await context.Database.MigrateAsync();
        Console.WriteLine($"✅ 应用了 {pendingMigrations.Count()} 个迁移");
    }
    else
    {
        Console.WriteLine("ℹ️ 没有待应用的迁移");
    }
    
    Console.WriteLine("🎉 数据库迁移完成！");
}
catch (Exception ex)
{
    Console.WriteLine($"❌ 数据库迁移失败: {ex.Message}");
    Console.WriteLine($"🔍 详细错误: {ex}");
    Environment.Exit(1);
} 